package com.yizhi.student.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yizhi.student.dao.StudentInfoDao;
import com.yizhi.student.domain.StudentInfoDO;
import com.yizhi.student.service.StudentInfoService;
import com.yizhi.system.domain.UserDO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class StudentInfoServiceImpl implements StudentInfoService {


	@Autowired
	private StudentInfoDao studentInfoDao;

	@Override
	public StudentInfoDO get(Integer id) {
		System.out.println("======service层中传递过来的id参数是：" + id + "======");
		return studentInfoDao.get(id);
	}


	@Override
	public List<StudentInfoDO> list(Map<String, Object> map) {
		//List<StudentInfoDO> studentInfoDOList = new ArrayList<>();
		return studentInfoDao.list(map);
	}

	//"===================================================================================="


	@Override
	public int count(Map<String, Object> map) {
		return studentInfoDao.count(map);
	}

	private Integer getByCertify(String certify) {
		return studentInfoDao.getIdByCertify(certify);
	}

	@Override
	public int save(StudentInfoDO studentInfo) {
		Integer studentIdDb = getByCertify(studentInfo.getCertify());
		if (ObjectUtil.isNotNull(studentIdDb)) {
			return -1;
		}
		Object principal = SecurityUtils.getSubject().getPrincipal();
		UserDO userDO = BeanUtil.copyProperties(principal, UserDO.class);
		// 查询了数据库，由于sys_user为从1开始的递增，这里直接转int
		studentInfo.setAddUserid(Math.toIntExact(userDO.getUserId()));
		studentInfo.setEditUserid(Math.toIntExact(userDO.getUserId()));
		Date date = new Date();
		studentInfo.setAddTime(date);
		studentInfo.setEditTime(date);
		//return studentInfoDao.save(studentInfo);
		studentInfoDao.save(studentInfo);

		return 1;
	}


	@Override
	public int update(StudentInfoDO studentInfo) {
		StudentInfoDO studentInfoDODb = get(studentInfo.getId());
		if (ObjectUtil.isEmpty(studentInfoDODb.getId())) {
			throw new RuntimeException("操作非法");
		}

		studentInfo.setEditTime(new Date());
		Object principal = SecurityUtils.getSubject().getPrincipal();
		UserDO userDO = BeanUtil.copyProperties(principal, UserDO.class);
		studentInfo.setEditUserid(Math.toIntExact(userDO.getUserId()));
		return studentInfoDao.update(studentInfo);
	}

	@Override
	public int remove(Integer id) {
		return studentInfoDao.remove(id);
	}

	@Override
	public int batchRemove(Integer[] ids) {
		return studentInfoDao.batchRemove(ids);
	}

}
